import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../utils/logger.dart';
import '../exceptions/app_exceptions.dart';

enum ViewState { idle, loading, error, empty, success }

abstract class BaseController extends GetxController {
  // 页面状态
  final _viewState = ViewState.idle.obs;
  ViewState get viewState => _viewState.value;
  
  // 错误信息
  final _errorMessage = ''.obs;
  String get errorMessage => _errorMessage.value;
  
  // 加载状态
  bool get isLoading => _viewState.value == ViewState.loading;
  bool get isError => _viewState.value == ViewState.error;
  bool get isEmpty => _viewState.value == ViewState.empty;
  bool get isSuccess => _viewState.value == ViewState.success;
  bool get isIdle => _viewState.value == ViewState.idle;
  
  // 页面标题
  final _title = ''.obs;
  String get title => _title.value;
  
  // 是否启用刷新
  final _enableRefresh = true.obs;
  bool get enableRefresh => _enableRefresh.value;
  
  // 是否启用加载更多
  final _enableLoadMore = true.obs;
  bool get enableLoadMore => _enableLoadMore.value;
  
  @override
  void onInit() {
    super.onInit();
    AppLogger.lifecycle('onInit', runtimeType.toString());
    initController();
  }
  
  @override
  void onReady() {
    super.onReady();
    AppLogger.lifecycle('onReady', runtimeType.toString());
    onControllerReady();
  }
  
  @override
  void onClose() {
    AppLogger.lifecycle('onClose', runtimeType.toString());
    onControllerClose();
    super.onClose();
  }
  
  // 子类可重写的方法
  void initController() {}
  void onControllerReady() {}
  void onControllerClose() {}
  
  // 设置页面状态
  void setViewState(ViewState state) {
    print('Setting view state to: $state');
    _viewState.value = state;
    AppLogger.debug('View state changed to: $state');
    update(['simple_list', 'tab_list']); // 更新特定id的GetBuilder
  }
  
  // 设置错误信息
  void setErrorMessage(String message) {
    _errorMessage.value = message;
    setViewState(ViewState.error);
    AppLogger.error('Error: $message');
  }
  
  // 设置页面标题
  void setTitle(String title) {
    _title.value = title;
  }
  
  // 设置刷新状态
  void setEnableRefresh(bool enable) {
    _enableRefresh.value = enable;
  }
  
  // 设置加载更多状态
  void setEnableLoadMore(bool enable) {
    _enableLoadMore.value = enable;
  }
  
  // 显示加载状态
  void showLoading() {
    setViewState(ViewState.loading);
  }
  
  // 隐藏加载状态
  void hideLoading() {
    if (isLoading) {
      setViewState(ViewState.idle);
    }
  }
  
  // 显示成功状态
  void showSuccess() {
    setViewState(ViewState.success);
  }
  
  // 显示空状态
  void showEmpty() {
    setViewState(ViewState.empty);
  }
  
  // 显示错误状态
  void showError(String message) {
    setErrorMessage(message);
  }
  
  // 处理异常
  void handleException(dynamic exception) {
    AppException appException;
    
    if (exception is AppException) {
      appException = exception;
    } else {
      appException = ExceptionHandler.handleException(exception);
    }
    
    final message = ExceptionHandler.getErrorMessage(appException);
    showError(message);
  }
  
  // 执行异步操作
  Future<T?> performAsyncOperation<T>(
    Future<T> Function() operation, {
    bool showLoadingState = true,
    bool handleError = true,
    String? errorMessage,
  }) async {
    try {
      if (showLoadingState) {
        showLoading();
      }
      
      final result = await operation();
      
      if (showLoadingState) {
        hideLoading();
      }
      
      return result;
    } catch (e) {
      if (handleError) {
        if (errorMessage != null) {
          showError(errorMessage);
        } else {
          handleException(e);
        }
      }
      
      if (showLoadingState) {
        hideLoading();
      }
      
      return null;
    }
  }
  
  // 重试操作
  Future<void> retry() async {
    setViewState(ViewState.idle);
    await onRetry();
  }
  
  // 子类可重写的重试方法
  Future<void> onRetry() async {}
  
  // 刷新数据
  Future<void> refresh() async {
    await onRefresh();
  }
  
  // 子类可重写的刷新方法
  Future<void> onRefresh() async {}
  
  // 加载更多数据
  Future<void> loadMore() async {
    await onLoadMore();
  }
  
  // 子类可重写的加载更多方法
  Future<void> onLoadMore() async {}
  
  // 显示成功消息
  void showSuccessMessage(String message) {
    Get.snackbar(
      '成功',
      message,
      snackPosition: SnackPosition.TOP,
      backgroundColor: Get.theme.colorScheme.primary,
      colorText: Get.theme.colorScheme.onPrimary,
    );
  }
  
  // 显示错误消息
  void showErrorMessage(String message) {
    Get.snackbar(
      '错误',
      message,
      snackPosition: SnackPosition.TOP,
      backgroundColor: Get.theme.colorScheme.error,
      colorText: Get.theme.colorScheme.onError,
    );
  }
  
  // 显示警告消息
  void showWarningMessage(String message) {
    Get.snackbar(
      '警告',
      message,
      snackPosition: SnackPosition.TOP,
      backgroundColor: Get.theme.colorScheme.secondary,
      colorText: Get.theme.colorScheme.onSecondary,
    );
  }
  
  // 显示信息消息
  void showInfoMessage(String message) {
    Get.snackbar(
      '信息',
      message,
      snackPosition: SnackPosition.TOP,
    );
  }
  
  // 显示确认对话框
  Future<bool> showConfirmDialog({
    required String title,
    required String message,
    String confirmText = '确定',
    String cancelText = '取消',
  }) async {
    final result = await Get.dialog<bool>(
      AlertDialog(
        title: Text(title),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Get.back(result: false),
            child: Text(cancelText),
          ),
          TextButton(
            onPressed: () => Get.back(result: true),
            child: Text(confirmText),
          ),
        ],
      ),
    );
    
    return result ?? false;
  }
  
  // 显示加载对话框
  void showLoadingDialog({String message = '加载中...'}) {
    Get.dialog(
      AlertDialog(
        content: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            const CircularProgressIndicator(),
            const SizedBox(width: 16),
            Text(message),
          ],
        ),
      ),
      barrierDismissible: false,
    );
  }
  
  // 隐藏加载对话框
  void hideLoadingDialog() {
    if (Get.isDialogOpen ?? false) {
      Get.back();
    }
  }
  
  // 显示底部选择器
  Future<T?> showBottomSheet<T>({
    required Widget child,
    bool isScrollControlled = false,
    bool isDismissible = true,
    bool enableDrag = true,
  }) async {
    return await Get.bottomSheet<T>(
      child,
      isScrollControlled: isScrollControlled,
      isDismissible: isDismissible,
      enableDrag: enableDrag,
    );
  }
  
  // 页面跳转
  void toNamed(String routeName, {dynamic arguments}) {
    Get.toNamed(routeName, arguments: arguments);
  }
  
  // 替换当前页面
  void offNamed(String routeName, {dynamic arguments}) {
    Get.offNamed(routeName, arguments: arguments);
  }
  
  // 替换所有页面
  void offAllNamed(String routeName, {dynamic arguments}) {
    Get.offAllNamed(routeName, arguments: arguments);
  }
  
  // 返回上一页
  void back([dynamic result]) {
    Get.back(result: result);
  }
  
  // 获取路由参数
  dynamic get arguments => Get.arguments;
  
  // 获取查询参数
  Map<String, String?> get parameters => Get.parameters;
  
  // 获取当前路由
  String? get currentRoute => Get.currentRoute;
  
  // 日志记录
  void logInfo(String message) {
    AppLogger.info('[$runtimeType] $message');
  }
  
  void logDebug(String message) {
    AppLogger.debug('[$runtimeType] $message');
  }
  
  void logError(String message, [dynamic error, StackTrace? stackTrace]) {
    AppLogger.error('[$runtimeType] $message', error, stackTrace);
  }
  
  void logWarning(String message) {
    AppLogger.warning('[$runtimeType] $message');
  }
}